package com.ncepu.thumb.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.ncepu.thumb.constant.ThumbConstant;
import com.ncepu.thumb.utils.RedisKeyUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author simon_jiang
 * @version 1.0
 */
@Component
@Slf4j
public class SyncThumb2DBCompensatoryJob {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private SyncThumb2DBJob syncThumb2DBJob;

    @Scheduled(cron = "${compensatory.cron}")
    public void run() {
        Set<String> keys = redisTemplate.keys(RedisKeyUtil.getTempThumbKey("") + "*");
        HashSet<String> needHandleDateSet = new HashSet<>();
        keys.stream()
                .filter(ObjUtil::isNotEmpty)
                .forEach(key -> needHandleDateSet.add(key.substring(ThumbConstant.TEMP_THUMB_KEY_PREFIX.length())));

        if(CollUtil.isEmpty(needHandleDateSet)) {
            return;
        }

        // 执行补偿任务
        for(String date : needHandleDateSet) {
            syncThumb2DBJob.syncThumb2DBByDate(date);
        }
    }

}
